<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/3/2
 * Time: 下午12:15
 */

namespace app\api\repository;


use app\common\Model\PayLog;
use app\common\Model\UserBalance;
use app\common\Service;
use app\api\repository\UserRepository;

class PayLogRespository extends Service
{
    /**
     * @param $uid          用户id
     * @param $order_num    订单号
     * @param $balance_type 受影响的钱包
     * @param $pay_event    受影响钱包的事件
     * @param $pay_channel  支付渠道
     * @param $amount       支付金额
     * @return array|mixed|string
     * 1: 充值 2：下单 3：提现 4：收入     由何种操作产生
     */
    public function createPayLog($uid, $order_num,$balance_type,$pay_event,$pay_channel,$amount,$status = 0)
    {

        $model = model("app\common\Model\PayLog");

//        if($pay_event == '2' || $pay_event == '3'){
//            $amount =  -$amount;
//        }

        $user_balance = UserBalance::get(['uid' => $uid]);
        $current_balance = $user_balance->recharge_balance + $user_balance->withdraw_balance;

        $model->uid = $uid;
        $model->order_num = $order_num;
        $model->balance_type = $balance_type;
        $model->pay_event = $pay_event;
        $model->pay_channel = $pay_channel;
        $model->amount = $amount;
        $model->is_show = 1;
        $model->status = $status;
        $model->create_ip = '1.1.1.1';
        $model->current_balance = $current_balance - $amount;

        if ($model->save()) {
            return $model->getData();
        }

        return $model->getError();
    }

    /**
     *
     * 更新支付订单 记录状态
     */
    public function updateOrderPayedStatus($order_num = null, $order_id = null,$amount)
    {
        if ($order_num == null && $order_id == null) {
            return [
                'code' => '100031',
                'msg' => '订单号或订单ID只允许一个为空',
            ];
        }

        $model = model("app\common\Model\PayLog");

        if ($order_num == null) {
            $model->where('order_id', $order_id);
        }

        if ($order_id == null) {
            $model->where('order_num', $order_num);
        }
        $model->current_balance = $amount;
        $model->status = 1;

        $res = $model->isUpdate(true)->save();

        return [
            'code' => '000000',
            'data' => $res,
        ];
    }
}